package com.laundry.shared.analytics

import android.content.Context
import android.os.Bundle
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.crashlytics.FirebaseCrashlytics
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import java.util.*

/**
 * 数据统计分析管理器
 */
class AnalyticsManager(private val context: Context) {
    
    private val firebaseAnalytics = FirebaseAnalytics.getInstance(context)
    private val crashlytics = FirebaseCrashlytics.getInstance()
    
    /**
     * 记录用户行为事件
     */
    fun trackUserEvent(eventName: String, parameters: Map<String, Any> = emptyMap()) {
        val bundle = Bundle().apply {
            parameters.forEach { (key, value) ->
                when (value) {
                    is String -> putString(key, value)
                    is Int -> putInt(key, value)
                    is Long -> putLong(key, value)
                    is Double -> putDouble(key, value)
                    is Boolean -> putBoolean(key, value)
                    else -> putString(key, value.toString())
                }
            }
            putLong("timestamp", System.currentTimeMillis())
        }
        
        firebaseAnalytics.logEvent(eventName, bundle)
        
        // 同时记录到本地数据库用于离线分析
        saveEventToLocal(eventName, parameters)
    }
    
    /**
     * 记录页面访问
     */
    fun trackScreenView(screenName: String, screenClass: String) {
        val bundle = Bundle().apply {
            putString(FirebaseAnalytics.Param.SCREEN_NAME, screenName)
            putString(FirebaseAnalytics.Param.SCREEN_CLASS, screenClass)
            putLong("timestamp", System.currentTimeMillis())
        }
        
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW, bundle)
        
        trackUserEvent("screen_view", mapOf(
            "screen_name" to screenName,
            "screen_class" to screenClass
        ))
    }
    
    /**
     * 记录用户注册
     */
    fun trackUserRegistration(method: String, userId: String) {
        val bundle = Bundle().apply {
            putString(FirebaseAnalytics.Param.METHOD, method)
            putString("user_id", userId)
        }
        
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SIGN_UP, bundle)
        
        trackUserEvent("user_registration", mapOf(
            "method" to method,
            "user_id" to userId
        ))
    }
    
    /**
     * 记录用户登录
     */
    fun trackUserLogin(method: String, userId: String) {
        val bundle = Bundle().apply {
            putString(FirebaseAnalytics.Param.METHOD, method)
            putString("user_id", userId)
        }
        
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.LOGIN, bundle)
        
        // 设置用户属性
        firebaseAnalytics.setUserId(userId)
        
        trackUserEvent("user_login", mapOf(
            "method" to method,
            "user_id" to userId
        ))
    }
    
    /**
     * 记录搜索行为
     */
    fun trackSearch(searchTerm: String, category: String?, resultCount: Int) {
        val bundle = Bundle().apply {
            putString(FirebaseAnalytics.Param.SEARCH_TERM, searchTerm)
            category?.let { putString("category", it) }
            putInt("result_count", resultCount)
        }
        
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SEARCH, bundle)
        
        trackUserEvent("search", mapOf(
            "search_term" to searchTerm,
            "category" to (category ?: ""),
            "result_count" to resultCount
        ))
    }
    
    /**
     * 记录商品/服务查看
     */
    fun trackItemView(itemId: String, itemName: String, category: String, price: Double) {
        val bundle = Bundle().apply {
            putString(FirebaseAnalytics.Param.ITEM_ID, itemId)
            putString(FirebaseAnalytics.Param.ITEM_NAME, itemName)
            putString(FirebaseAnalytics.Param.ITEM_CATEGORY, category)
            putDouble(FirebaseAnalytics.Param.PRICE, price)
            putString(FirebaseAnalytics.Param.CURRENCY, "CNY")
        }
        
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM, bundle)
        
        trackUserEvent("item_view", mapOf(
            "item_id" to itemId,
            "item_name" to itemName,
            "category" to category,
            "price" to price
        ))
    }
    
    /**
     * 记录添加到购物车
     */
    fun trackAddToCart(itemId: String, itemName: String, category: String, price: Double, quantity: Int) {
        val bundle = Bundle().apply {
            putString(FirebaseAnalytics.Param.ITEM_ID, itemId)
            putString(FirebaseAnalytics.Param.ITEM_NAME, itemName)
            putString(FirebaseAnalytics.Param.ITEM_CATEGORY, category)
            putDouble(FirebaseAnalytics.Param.PRICE, price)
            putLong(FirebaseAnalytics.Param.QUANTITY, quantity.toLong())
            putString(FirebaseAnalytics.Param.CURRENCY, "CNY")
        }
        
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.ADD_TO_CART, bundle)
        
        trackUserEvent("add_to_cart", mapOf(
            "item_id" to itemId,
            "item_name" to itemName,
            "category" to category,
            "price" to price,
            "quantity" to quantity
        ))
    }
    
    /**
     * 记录开始结账
     */
    fun trackBeginCheckout(orderId: String, totalValue: Double, itemCount: Int) {
        val bundle = Bundle().apply {
            putString("order_id", orderId)
            putDouble(FirebaseAnalytics.Param.VALUE, totalValue)
            putString(FirebaseAnalytics.Param.CURRENCY, "CNY")
            putInt("item_count", itemCount)
        }
        
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.BEGIN_CHECKOUT, bundle)
        
        trackUserEvent("begin_checkout", mapOf(
            "order_id" to orderId,
            "total_value" to totalValue,
            "item_count" to itemCount
        ))
    }
    
    /**
     * 记录购买完成
     */
    fun trackPurchase(
        orderId: String,
        totalValue: Double,
        items: List<PurchaseItem>,
        paymentMethod: String
    ) {
        val bundle = Bundle().apply {
            putString(FirebaseAnalytics.Param.TRANSACTION_ID, orderId)
            putDouble(FirebaseAnalytics.Param.VALUE, totalValue)
            putString(FirebaseAnalytics.Param.CURRENCY, "CNY")
            putString("payment_method", paymentMethod)
            putInt("item_count", items.size)
        }
        
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.PURCHASE, bundle)
        
        trackUserEvent("purchase", mapOf(
            "order_id" to orderId,
            "total_value" to totalValue,
            "payment_method" to paymentMethod,
            "item_count" to items.size
        ))
    }
    
    /**
     * 记录分享行为
     */
    fun trackShare(contentType: String, contentId: String, method: String) {
        val bundle = Bundle().apply {
            putString(FirebaseAnalytics.Param.CONTENT_TYPE, contentType)
            putString(FirebaseAnalytics.Param.ITEM_ID, contentId)
            putString(FirebaseAnalytics.Param.METHOD, method)
        }
        
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SHARE, bundle)
        
        trackUserEvent("share", mapOf(
            "content_type" to contentType,
            "content_id" to contentId,
            "method" to method
        ))
    }
    
    /**
     * 记录评价行为
     */
    fun trackRating(itemId: String, rating: Int, hasComment: Boolean) {
        trackUserEvent("rating", mapOf(
            "item_id" to itemId,
            "rating" to rating,
            "has_comment" to hasComment
        ))
    }
    
    /**
     * 记录收藏行为
     */
    fun trackFavorite(itemId: String, itemType: String, action: String) {
        trackUserEvent("favorite", mapOf(
            "item_id" to itemId,
            "item_type" to itemType,
            "action" to action // add, remove
        ))
    }
    
    /**
     * 记录客服咨询
     */
    fun trackCustomerService(sessionId: String, type: String, resolved: Boolean) {
        trackUserEvent("customer_service", mapOf(
            "session_id" to sessionId,
            "type" to type,
            "resolved" to resolved
        ))
    }
    
    /**
     * 记录应用崩溃
     */
    fun trackCrash(exception: Throwable, context: String) {
        crashlytics.recordException(exception)
        crashlytics.setCustomKey("crash_context", context)
        
        trackUserEvent("app_crash", mapOf(
            "exception_type" to exception.javaClass.simpleName,
            "exception_message" to (exception.message ?: ""),
            "context" to context
        ))
    }
    
    /**
     * 记录性能指标
     */
    fun trackPerformance(metricName: String, value: Long, attributes: Map<String, String> = emptyMap()) {
        trackUserEvent("performance", mapOf(
            "metric_name" to metricName,
            "value" to value
        ) + attributes)
    }
    
    /**
     * 设置用户属性
     */
    fun setUserProperty(name: String, value: String) {
        firebaseAnalytics.setUserProperty(name, value)
    }
    
    /**
     * 设置用户ID
     */
    fun setUserId(userId: String) {
        firebaseAnalytics.setUserId(userId)
        crashlytics.setUserId(userId)
    }
    
    /**
     * 获取用户行为统计
     */
    suspend fun getUserBehaviorStats(userId: String, days: Int = 30): Flow<UserBehaviorStats> = flow {
        try {
            // 从本地数据库获取用户行为统计
            val stats = calculateUserBehaviorStats(userId, days)
            emit(stats)
        } catch (e: Exception) {
            trackCrash(e, "getUserBehaviorStats")
            emit(UserBehaviorStats())
        }
    }
    
    /**
     * 获取应用使用统计
     */
    suspend fun getAppUsageStats(days: Int = 30): Flow<AppUsageStats> = flow {
        try {
            val stats = calculateAppUsageStats(days)
            emit(stats)
        } catch (e: Exception) {
            trackCrash(e, "getAppUsageStats")
            emit(AppUsageStats())
        }
    }
    
    /**
     * 获取商业指标统计
     */
    suspend fun getBusinessMetrics(days: Int = 30): Flow<BusinessMetrics> = flow {
        try {
            val metrics = calculateBusinessMetrics(days)
            emit(metrics)
        } catch (e: Exception) {
            trackCrash(e, "getBusinessMetrics")
            emit(BusinessMetrics())
        }
    }
    
    // 私有方法
    private fun saveEventToLocal(eventName: String, parameters: Map<String, Any>) {
        // 保存事件到本地SQLite数据库
        // 用于离线分析和数据备份
    }
    
    private fun calculateUserBehaviorStats(userId: String, days: Int): UserBehaviorStats {
        // 从本地数据库计算用户行为统计
        return UserBehaviorStats(
            totalSessions = 0,
            averageSessionDuration = 0L,
            totalScreenViews = 0,
            totalSearches = 0,
            totalPurchases = 0,
            totalSpent = 0.0,
            favoriteCategories = emptyList(),
            mostUsedFeatures = emptyList()
        )
    }
    
    private fun calculateAppUsageStats(days: Int): AppUsageStats {
        // 计算应用使用统计
        return AppUsageStats(
            totalUsers = 0,
            activeUsers = 0,
            newUsers = 0,
            retentionRate = 0.0,
            averageSessionDuration = 0L,
            crashRate = 0.0,
            popularScreens = emptyList(),
            popularFeatures = emptyList()
        )
    }
    
    private fun calculateBusinessMetrics(days: Int): BusinessMetrics {
        // 计算商业指标
        return BusinessMetrics(
            totalRevenue = 0.0,
            totalOrders = 0,
            averageOrderValue = 0.0,
            conversionRate = 0.0,
            customerAcquisitionCost = 0.0,
            customerLifetimeValue = 0.0,
            topSellingServices = emptyList(),
            revenueByCategory = emptyMap()
        )
    }
}

// 数据模型
data class PurchaseItem(
    val itemId: String,
    val itemName: String,
    val category: String,
    val price: Double,
    val quantity: Int
)

data class UserBehaviorStats(
    val totalSessions: Int = 0,
    val averageSessionDuration: Long = 0,
    val totalScreenViews: Int = 0,
    val totalSearches: Int = 0,
    val totalPurchases: Int = 0,
    val totalSpent: Double = 0.0,
    val favoriteCategories: List<String> = emptyList(),
    val mostUsedFeatures: List<String> = emptyList()
)

data class AppUsageStats(
    val totalUsers: Int = 0,
    val activeUsers: Int = 0,
    val newUsers: Int = 0,
    val retentionRate: Double = 0.0,
    val averageSessionDuration: Long = 0,
    val crashRate: Double = 0.0,
    val popularScreens: List<String> = emptyList(),
    val popularFeatures: List<String> = emptyList()
)

data class BusinessMetrics(
    val totalRevenue: Double = 0.0,
    val totalOrders: Int = 0,
    val averageOrderValue: Double = 0.0,
    val conversionRate: Double = 0.0,
    val customerAcquisitionCost: Double = 0.0,
    val customerLifetimeValue: Double = 0.0,
    val topSellingServices: List<String> = emptyList(),
    val revenueByCategory: Map<String, Double> = emptyMap()
)
